package com.apes.autoparts.searcher.vin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.searcher.repository.AutopartsDao;
import com.apes.framework.api.DomainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class KeywordSearcher extends DomainService {
    @Autowired
    AutopartsDao autopartsDao;

    /***
     * 解析关键词
     * 1. 通过配件名称或者配件倒推子组
     * @param param
     * @return
     */
    public Map searchKeyword(JSONObject param) {
        Map returnMap = new HashMap();
        JSONArray menuIdArray;

        JSONArray tempArray = autopartsDao.parseKeywordForPartNumber(param);

        if (tempArray == null || tempArray.size() == 0) {
            tempArray = autopartsDao.parseKeywordPartDescId(param);
        }

        menuIdArray = new JSONArray(tempArray.stream().map(json -> ((JSONObject) json).getString("CURRENT_ID")).collect(Collectors.toList()));

        JSONArray subgroups = menuIdArray.size() == 0 ?  menuIdArray : autopartsDao.getSubgroupForEpc(param, menuIdArray);

        subgroups = subgroups.stream().map(json -> {
            JSONObject tempJson = (JSONObject) json;
            return this.invoke("autoparts.catalogConvert", tempJson);
        }).collect(Collectors.toCollection(JSONArray::new));


        returnMap.put("data",subgroups);
        returnMap.put("dataSource", "INNER");

        return returnMap;
    }


    /***
     * 解析目录名
     */
    public Map searchMenuName(JSONObject param) {
        Map returnMap = new HashMap();
        JSONArray menuIdArray;

        JSONArray subgroups = autopartsDao.getSubgroupByMenuName(param);

        subgroups = subgroups.stream().map(json -> {
            JSONObject tempJson = (JSONObject) json;
            return this.invoke("autoparts.catalogConvert", tempJson);
        }).collect(Collectors.toCollection(JSONArray::new));

        returnMap.put("data",subgroups);
        returnMap.put("dataSource", "INNER");
        return  returnMap;
    }
}
